package com.yineng.message.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import com.yineng.message.mail.inter.MailCoreInter;

public class MailCore implements MailCoreInter{
	
	static Logger logger = Logger.getLogger(MailCore.class.getName());
	
	
	
	/**
	 * 简单邮件发送接口
	 * 
	 * @param from 				发送者邮箱地址,如: hesheng@yineng.com
	 * 
	 * @param from user			发送者邮箱  用户名
	 * 
	 * @param from password		发送者邮箱  密码
	 * 
	 * @param to 				收件者邮箱地址,如: hesheng@yineng.com
	 *            
	 * @param subject 			邮件主题
	 * 
	 * @param text    			邮件内容
	 * 
	 * @param smtpHost			SMTP 服务器
	 * 
	 * @param smtpPort			SMTP 服务器端口
	 * 
	 * @param isDebug			是否  debug 发送邮件过程
	 * 
	 * @author hesheng
	 * 
	 * @date Nov 26, 2010
	 * 
	 * @exception Exception
	 **/
	public boolean simpleMail(String from,final String fromUser,final String fromPwd, String to, String subject, String text,
			String smtpHost, String smtpPort, boolean isDebug) {
			logger.debug("from : "+from);
			logger.debug("fromUser : "+fromUser);
			logger.debug("fromPwd"+fromPwd);
			logger.debug("to : "+to);
			logger.debug("subject : "+subject);
			logger.debug("text : "+text);
			logger.debug("smtpHost : "+smtpHost);
			logger.debug("smtpPort : "+smtpPort);
			logger.debug("isDebug : "+isDebug);
			
		    Properties properties = new Properties();
		    properties.put("mail.smtp.host", smtpHost);
		    properties.put("mail.smtp.port", smtpPort);
		    properties.put("mail.smtp.auth","true");  
		    Session session = Session.getDefaultInstance(properties, new Authenticator(){
		    	  
		    	public PasswordAuthentication getPasswordAuthentication() {  
		    		return new PasswordAuthentication(fromUser, fromPwd);  
		    	} 
		    });
		    session.setDebug(isDebug);
		    boolean status = true;
		    Message message = new MimeMessage(session);
		    try {
				message.setFrom(new InternetAddress(from));
				message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
				message.setSubject(subject);
				message.setText(text);
				Transport.send(message);
			} catch (AddressException e) {
				e.printStackTrace();
				status = false;
			} catch (MessagingException e) {
				e.printStackTrace();
				status = false;
			}finally{
				return status;
			}
		
	}
}
